package com.jinlejia.erp.lab;

import android.content.Context;
import android.content.Intent;

import com.jinlejia.bbs.bean.db.BbsSearchHistoryBean;
import com.jinlejia.erp.base.unicorn.UnicornUtils;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.ui.common.LoginActivity;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.SharePTool;
import com.jinlejia.feedback.idea.ui.bean.FbSearchQuestionHistoryBean;
import com.lab.user.LabLogonCallBack;
import com.lab.user.LabUserInfo;
import com.lab.user.UserLifecycle;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.nimlib.utils.NimIMUtils;
import com.qiyukf.unicorn.api.Unicorn;
import com.tencent.bugly.crashreport.CrashReport;

import org.jetbrains.annotations.NotNull;

import cn.jpush.android.api.JPushInterface;


/**
 *
 */
public class UserLifecycleImpl implements UserLifecycle {
    @Override
    public void onLogout(@NotNull Context context) {
        //删除用户存储的信息
        //1. 删除Cookie信息
        DbUtil.getDB(context).single().deleteAll(SaveCookieBean.class);
        //2. 删除意见反馈信息
        DbUtil.getDB(context).single().deleteAll(FbSearchQuestionHistoryBean.class);
        //3. 删除社区信息
        DbUtil.getDB(context).single().deleteAll(BbsSearchHistoryBean.class);
        //4. 七鱼退出
        Unicorn.logout();
        //5. 删除首选项信息
        SharePTool.deleteUserInfoBean(context);
        //6. 停止极光推送
        JPushInterface.stopPush(context);
        //7. 网易云信退出
        NimIMUtils.logout(context);
        //跳转至登录页面
        Intent Intent1 = new Intent(context, LoginActivity.class);
        Intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent1);
    }

    @Override
    public void onLogon(@NotNull Context context, @NotNull LabUserInfo labUserInfo, @NotNull LabLogonCallBack loginCallback) {
        SharePTool.UserInfoBean bean = (SharePTool.UserInfoBean) labUserInfo;
        //1. 保存用户的cookie 和 pin
        DbUtil.getDB(context).single().save(new SaveCookieBean(200, bean.getCookie()));
        DbUtil.getDB(context).single().save(new SaveCookieBean(202, bean.getPin()));
        //2. bugly 设置用户ID
        String pin = bean.getPin();
        CrashReport.setUserId(pin);
        //3. 注册 网易七鱼
        UnicornUtils.registerUnicorn(bean);
        //4. 尝试登录 网易云信
        NimIMUtils.login(context,false, bean.getPin(), new RequestCallbackWrapper<String>() {
            @Override
            public void onResult(int code, String result, Throwable exception) {
                loginCallback.loginSuccess();
            }
        });
    }
}
